home *** CD-ROM | disk | FTP | other *** search
/ BBS in a Box 5 / BBS in a Box -Volume V (BBS in a Box) (April 1992).iso / Files / Prog / M / MPWGCC (Misc).cpt / Bison / Documents / Info / bison.info-2 < prev    next >
Encoding:
Text File  |  1989-05-30  |  48.3 KB  |  1,385 lines  |  [TEXT/MPS ]

  1. Info file bison.info, produced by Makeinfo, -*- Text -*- from input
  2. file bison.texinfo.
  3.  
  4. This file documents the Bison parser generator.
  5.  
  6. Copyright (C) 1988, 1989 Free Software Foundation, Inc.
  7.  
  8. Permission is granted to make and distribute verbatim copies of this
  9. manual provided the copyright notice and this permission notice are
  10. preserved on all copies.
  11.  
  12. Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided also
  14. that the sections entitled ``GNU General Public License'' and
  15. ``Conditions for Using Bison'' are included exactly as in the
  16. original, and provided that the entire resulting derived work is
  17. distributed under the terms of a permission notice identical to this
  18. one.
  19.  
  20. Permission is granted to copy and distribute translations of this
  21. manual into another language, under the above conditions for modified
  22. versions, except that the sections entitled ``GNU General Public
  23. License'', ``Conditions for Using Bison'' and this permission notice
  24. may be included in translations approved by the Free Software
  25. Foundation instead of in the original English.
  26.  
  27.  
  28. 
  29. File: bison.info,  Node: Infix Calc,  Next: Simple Error Recovery,  Prev: RPN Calc,  Up: Top
  30.  
  31. Infix Notation Calculator: `calc'
  32. =================================
  33.  
  34. We now modify rpcalc to handle infix operators instead of postfix. 
  35. Infix notation involves the concept of operator precedence and the
  36. need for parentheses nested to arbitrary depth.  Here is the Bison
  37. code for `calc.y', an infix desk-top calculator.
  38.  
  39.      /* Infix notation calculator--calc */
  40.      
  41.      %{
  42.      #define YYSTYPE double
  43.      #include <math.h>
  44.      %}
  45.      
  46.      %token NUM
  47.      %left '-' '+'
  48.      %left '*' '/'
  49.      %left NEG     /* negation--unary minus */
  50.      %right '^'    /* exponentiation        */
  51.      
  52.      /* Grammar follows */
  53.      %%
  54.      input:    /* empty string */
  55.              | input line
  56.      ;
  57.      
  58.      line:     '\n'
  59.              | exp '\n'  { printf("\t%.10g\n", $1); }
  60.      ;
  61.      
  62.      exp:      NUM                { $$ = $1;         }
  63.              | exp '+' exp        { $$ = $1 + $3;    }
  64.              | exp '-' exp        { $$ = $1 - $3;    }
  65.              | exp '*' exp        { $$ = $1 * $3;    }
  66.              | exp '/' exp        { $$ = $1 / $3;    }
  67.              | '-' exp  %prec NEG { $$ = -$2;        }
  68.              | exp '^' exp        { $$ = pow ($1, $3); }
  69.              | '(' exp ')'        { $$ = $2;         }
  70.      ;
  71.      %%
  72.  
  73. The functions `yylex', `yyerror' and `main' can be the same as before.
  74.  
  75. There are two important new features shown in this code.
  76.  
  77. In the second section (Bison declarations), `%left' declares token
  78. types and says they are left-associative operators.  The declarations
  79. `%left' and `%right' (right associativity) take the place of `%token'
  80. which is used to declare a token type name without associativity. 
  81. (These tokens are single-character literals, which ordinarily don't
  82. need to be declared.  We declare them here to specify the
  83. associativity.)
  84.  
  85. Operator precedence is determined by the line ordering of the
  86. declarations; the lower the declaration, the higher the precedence. 
  87. Hence, exponentiation has the highest precedence, unary minus (`NEG')
  88. is next, followed by `*' and `/', and so on.  *Note Precedence::.
  89.  
  90. The other important new feature is the `%prec' in the grammar section
  91. for the unary minus operator.  The `%prec' simply instructs Bison
  92. that the rule `| '-' exp' has the same precedence as `NEG'--in this
  93. case the next-to-highest.  *Note Contextual Precedence::.
  94.  
  95. Here is a sample run of `calc.y':
  96.  
  97.      % calc
  98.      4 + 4.5 - (34/(8*3+-3))
  99.      6.880952381
  100.      -56 + 2
  101.      -54
  102.      3 ^ 2
  103.      9
  104.  
  105.  
  106. 
  107. File: bison.info,  Node: Simple Error Recovery,  Next: Multi-function Calc,  Prev: Infix Calc,  Up: Examples
  108.  
  109. Simple Error Recovery
  110. =====================
  111.  
  112. Up to this point, this manual has not addressed the issue of "error
  113. recovery"--how to continue parsing after the parser detects a syntax
  114. error.  All we have handled is error reporting with `yyerror'. 
  115. Recall that by default `yyparse' returns after calling `yyerror'. 
  116. This means that an erroneous input line causes the calculator program
  117. to exit.  Now we show how to rectify this deficiency.
  118.  
  119. The Bison language itself includes the reserved word `error', which
  120. may be included in the grammar rules.  In the example below it has
  121. been added to one of the alternatives for `line':
  122.  
  123.      line:     '\n'
  124.              | exp '\n'   { printf("\t%.10g\n", $1); }
  125.              | error '\n' { yyerrok;                 }
  126.      ;
  127.  
  128. This addition to the grammar allows for simple error recovery in the
  129. event of a parse error.  If an expression that cannot be evaluated is
  130. read, the error will be recognized by the third rule for `line', and
  131. parsing will continue.  (The `yyerror' function is still called upon
  132. to print its message as well.)  The action executes the statement
  133. `yyerrok', a macro defined automatically by Bison; its meaning is
  134. that error recovery is complete (*note Error Recovery::.).  Note the
  135. difference between `yyerrok' and `yyerror'; neither one is a misprint.
  136.  
  137. This form of error recovery deals with syntax errors.  There are
  138. other kinds of errors; for example, division by zero, which raises an
  139. exception signal that is normally fatal.  A real calculator program
  140. must handle this signal and use `longjmp' to return to `main' and
  141. resume parsing input lines; it would also have to discard the rest of
  142. the current line of input.  We won't discuss this issue further
  143. because it is not specific to Bison programs.
  144.  
  145.  
  146. 
  147. File: bison.info,  Node: Multi-function Calc,  Prev: Simple Error Recovery,  Up: Examples
  148.  
  149. Multi-Function Calculator: `mfcalc'
  150. ===================================
  151.  
  152. Now that the basics of Bison have been discussed, it is time to move
  153. on to a more advanced problem.  The above calculators provided only
  154. five functions, `+', `-', `*', `/' and `^'.  It would be nice to have
  155. a calculator that provides other mathematical functions such as
  156. `sin', `cos', etc.
  157.  
  158. It is easy to add new operators to the infix calculator as long as
  159. they are only single-character literals.  The lexical analyzer
  160. `yylex' passes back all non-number characters as tokens, so new
  161. grammar rules suffice for adding a new operator.  But we want
  162. something more flexible: built-in functions whose syntax has this form:
  163.  
  164.      FUNCTION_NAME (ARGUMENT)
  165.  
  166. At the same time, we will add memory to the calculator, by allowing
  167. you to create named variables, store values in them, and use them
  168. later.  Here is a sample session with the multi-function calculator:
  169.  
  170.      % acalc
  171.      pi = 3.141592653589
  172.      3.1415926536
  173.      sin(pi)
  174.      0.0000000000
  175.      alpha = beta1 = 2.3
  176.      2.3000000000
  177.      alpha
  178.      2.3000000000
  179.      ln(alpha)
  180.      0.8329091229
  181.      exp(ln(beta1))
  182.      2.3000000000
  183.      %
  184.  
  185. Note that multiple assignment and nested function calls are permitted.
  186.  
  187. * Menu:
  188.  
  189. * Decl: Mfcalc Decl.     Bison declarations for multi-function calculator.
  190. * Rules: Mfcalc Rules.   Grammar rules for the calculator.
  191. * Symtab: Mfcalc Symtab. Symbol table management subroutines.
  192.  
  193.  
  194. 
  195. File: bison.info,  Node: Mfcalc Decl,  Next: Mfcalc Rules,  Prev: Multi-function Calc,  Up: Multi-function Calc
  196.  
  197. Declarations for `mfcalc'
  198. -------------------------
  199.  
  200. Here are the C and Bison declarations for the multi-function
  201. calculator.
  202.  
  203.      %{
  204.      #include <math.h>  /* For math functions, cos(), sin(), etc      */
  205.      #include "calc.h"  /* Contains definition of `symrec' */
  206.      %}
  207.      %union {
  208.      double     val;  /* For returning numbers.              */
  209.      symrec  *tptr;   /* For returning symbol-table pointers */
  210.      }
  211.      
  212.      %token <val>  NUM        /* Simple double precision number  */
  213.      %token <tptr> VAR FNCT   /* Variable and Function           */
  214.      %type  <val>  exp
  215.      
  216.      %right '='
  217.      %left '-' '+'
  218.      %left '*' '/'
  219.      %left NEG     /* Negation--unary minus */
  220.      %right '^'    /* Exponentiation        */
  221.      
  222.      /* Grammar follows */
  223.      
  224.      %%
  225.  
  226. The above grammar introduces only two new features of the Bison
  227. language.  These features allow semantic values to have various data
  228. types (*note Multiple Types::.).
  229.  
  230. The `%union' declaration specifies the entire list of possible types;
  231. this is instead of defining `YYSTYPE'.  The allowable types are now
  232. double-floats (for `exp' and `NUM') and pointers to entries in the
  233. symbol table.  *Note Union Decl::.
  234.  
  235. Since values can now have various types, it is necessary to associate
  236. a type with each grammar symbol whose semantic value is used.  These
  237. symbols are `NUM', `VAR', `FNCT', and `exp'.  Their declarations are
  238. augmented with information about their data type (placed between
  239. angle brackets).
  240.  
  241. The Bison construct `%type' is used for declaring nonterminal
  242. symbols, just as `%token' is used for declaring token types.  We have
  243. not used `%type' before because nonterminal symbols are normally
  244. declared implicitly by the rules that define them.  But `exp' must be
  245. declared explicitly so we can specify its value type.  *Note Type
  246. Decl::.
  247.  
  248.  
  249. 
  250. File: bison.info,  Node: Mfcalc Rules,  Next: Mfcalc Symtab,  Prev: Mfcalc Decl,  Up: Multi-function Calc
  251.  
  252. Grammar Rules for `mfcalc'
  253. --------------------------
  254.  
  255. Here are the grammar rules for the multi-function calculator.  Most
  256. of them are copied directly from `calc'; three rules, those which
  257. mention `VAR' or `FNCT', are new.
  258.  
  259.      input:   /* empty */
  260.              | input line
  261.      ;
  262.      
  263.      line:
  264.                '\n'
  265.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  266.              | error '\n' { yyerrok;                  }
  267.      ;
  268.      
  269.      exp:      NUM                { $$ = $1;                         }
  270.              | VAR                { $$ = $1->value.var;              }
  271.              | VAR '=' exp        { $$ = $3; $1->value.var = $3;     }
  272.              | FNCT '(' exp ')'   { $$ = (*($1->value.fnctptr))($3); }
  273.              | exp '+' exp        { $$ = $1 + $3;                    }
  274.              | exp '-' exp        { $$ = $1 - $3;                    }
  275.              | exp '*' exp        { $$ = $1 * $3;                    }
  276.              | exp '/' exp        { $$ = $1 / $3;                    }
  277.              | '-' exp  %prec NEG { $$ = -$2;                        }
  278.              | exp '^' exp        { $$ = pow ($1, $3);               }
  279.              | '(' exp ')'        { $$ = $2;                         }
  280.      ;
  281.      /* End of grammar */
  282.      %%
  283.  
  284.  
  285. 
  286. File: bison.info,  Node: Mfcalc Symtab,  Prev: Mfcalc Rules,  Up: Multi-function Calc
  287.  
  288. Managing the Symbol Table for `mfcalc'
  289. --------------------------------------
  290.  
  291. The multi-function calculator requires a symbol table to keep track
  292. of the names and meanings of variables and functions.  This doesn't
  293. affect the grammar rules (except for the actions) or the Bison
  294. declarations, but it requires some additional C functions for support.
  295.  
  296. The symbol table itself consists of a linked list of records.  Its
  297. definition, which is kept in the header `calc.h', is as follows.  It
  298. provides for either functions or variables to be placed in the table.
  299.  
  300.      /* Data type for links in the chain of symbols.  */
  301.      struct symrec
  302.      {
  303.        char *name;  /* name of symbol              */
  304.        int type;    /* type of symbol: either VAR or FNCT */
  305.        union {
  306.          double var;           /* value of a VAR  */
  307.          double (*fnctptr)();  /* value of a FNCT */
  308.        } value;
  309.        struct symrec *next;    /* link field    */
  310.      };
  311.      
  312.      typedef struct symrec symrec;
  313.      
  314.      /* The symbol table: a chain of `struct symrec'.  */
  315.      extern symrec *sym_table;
  316.      
  317.      symrec *putsym ();
  318.      symrec *getsym ();
  319.  
  320. The new version of `main' includes a call to `init_table', a function
  321. that initializes the symbol table.  Here it is, and `init_table' as
  322. well:
  323.  
  324.      #include <stdio.h>
  325.      
  326.      main()
  327.      {
  328.        init_table ();
  329.        yyparse ();
  330.      }
  331.      
  332.      yyerror (s)  /* Called by yyparse on error */
  333.           char *s;
  334.      {
  335.        printf ("%s\n", s);
  336.      }
  337.      
  338.      struct init
  339.      {
  340.        char *fname;
  341.        double (*fnct)();
  342.      };
  343.      
  344.      struct init arith_fncts[]
  345.        = {
  346.            "sin", sin,
  347.            "cos", cos,
  348.            "atan", atan,
  349.            "ln", log,
  350.            "exp", exp,
  351.            "sqrt", sqrt,
  352.            0, 0
  353.          };
  354.      
  355.      /* The symbol table: a chain of `struct symrec'.  */
  356.      symrec *sym_table = (symrec *)0;
  357.      
  358.      init_table ()  /* puts arithmetic functions in table. */
  359.      {
  360.        int i;
  361.        symrec *ptr;
  362.        for (i = 0; arith_fncts[i].fname != 0; i++)
  363.          {
  364.            ptr = putsym (arith_fncts[i].fname, FNCT);
  365.            ptr->value.fnctptr = arith_fncts[i].fnct;
  366.          }
  367.      }
  368.  
  369. By simply editing the initialization list and adding the necessary
  370. include files, you can add additional functions to the calculator.
  371.  
  372. Two important functions allow look-up and installation of symbols in
  373. the symbol table.  The function `putsym' is passed a name and the
  374. type (`VAR' or `FNCT') of the object to be installed.  The object is
  375. linked to the front of the list, and a pointer to the object is
  376. returned.  The function `getsym' is passed the name of the symbol to
  377. look up.  If found, a pointer to that symbol is returned; otherwise
  378. zero is returned.
  379.  
  380.      symrec *
  381.      putsym (sym_name,sym_type)
  382.           char *sym_name;
  383.           int sym_type;
  384.      {
  385.        symrec *ptr;
  386.        ptr = (symrec *) malloc (sizeof(symrec));
  387.        ptr->name = (char *) malloc (strlen(sym_name)+1);
  388.        strcpy (ptr->name,sym_name);
  389.        ptr->type = sym_type;
  390.        ptr->value.var = 0; /* set value to 0 even if fctn.  */
  391.        ptr->next = (struct symrec *)sym_table;
  392.        sym_table = ptr;
  393.        return ptr;
  394.      }
  395.      
  396.      symrec *
  397.      getsym (sym_name)
  398.           char *sym_name;
  399.      {
  400.        symrec *ptr;
  401.        for (ptr = sym_table; ptr != (symrec *) 0;
  402.             ptr = (symrec *)ptr->next)
  403.          if (strcmp (ptr->name,sym_name) == 0)
  404.            return ptr;
  405.        return 0;
  406.      }
  407.  
  408. The function `yylex' must now recognize variables, numeric values,
  409. and the single-character arithmetic operators.  Strings of
  410. alphanumeric characters with a leading nondigit are recognized as
  411. either variables or functions depending on what the symbol table says
  412. about them.
  413.  
  414. The string is passed to `getsym' for look up in the symbol table.  If
  415. the name appears in the table, a pointer to its location and its type
  416. (`VAR' or `FNCT') is returned to `yyparse'.  If it is not already in
  417. the table, then it is installed as a `VAR' using `putsym'.  Again, a
  418. pointer and its type (which must be `VAR') is returned to `yyparse'.
  419.  
  420. No change is needed in the handling of numeric values and arithmetic
  421. operators in `yylex'.
  422.  
  423.      #include <ctype.h>
  424.      yylex()
  425.      {
  426.        int c;
  427.      
  428.        /* Ignore whitespace, get first nonwhite character.  */
  429.        while ((c = getchar ()) == ' ' || c == '\t');
  430.      
  431.        if (c == EOF)
  432.          return 0;
  433.      
  434.        /* Char starts a number => parse the number.  */
  435.        if (c == '.' || isdigit (c))
  436.          {
  437.            ungetc (c, stdin);
  438.            scanf ("%lf", &yylval.val);
  439.            return NUM;
  440.          }
  441.      
  442.        /* Char starts an identifier => read the name.  */
  443.        if (isalpha (c))
  444.          {
  445.            symrec *s;
  446.            static char *symbuf = 0;
  447.            static int length = 0;
  448.            int i;
  449.      
  450.            /* Initially make the buffer long enough
  451.               for a 40-character symbol name.  */
  452.            if (length == 0)
  453.              length = 40, symbuf = (char *)malloc (length + 1);
  454.      
  455.            i = 0;
  456.            do
  457.              {
  458.                /* If buffer is full, make it bigger.  */
  459.                if (i == length)
  460.                  {
  461.                    length *= 2;
  462.                    symbuf = (char *)realloc (symbuf, length + 1);
  463.                  }
  464.                /* Add this character to the buffer.  */
  465.                symbuf[i++] = c;
  466.                /* Get another character.  */
  467.                c = getchar ();
  468.              }
  469.            while (c != EOF && isalnum (c));
  470.      
  471.            ungetc (c, stdin);
  472.            symbuf[i] = '\0';
  473.      
  474.            s = getsym (symbuf);
  475.            if (s == 0)
  476.              s = putsym (symbuf, VAR);
  477.            yylval.tptr = s;
  478.            return s->type;
  479.          }
  480.      
  481.        /* Any other character is a token by itself.  */
  482.        return c;
  483.      }
  484.  
  485. This program is both powerful and flexible. You may easily add new
  486. functions, and it is a simple job to modify this code to install
  487. predefined variables such as `pi' or `e' as well.
  488.  
  489.  
  490. 
  491. File: bison.info,  Node: Exercises,  Prev: Multi-function calc,  Up: Examples
  492.  
  493. Exercises
  494. =========
  495.  
  496.   1. Add some new functions from `math.h' to the initialization list.
  497.  
  498.   2. Add another array that contains constants and their values. 
  499.      Then modify `init_table' to add these constants to the symbol
  500.      table.  It will be easiest to give the constants type `VAR'.
  501.  
  502.   3. Make the program report an error if the user refers to an
  503.      uninitialized variable in any way except to store a value in it.
  504.  
  505.  
  506. 
  507. File: bison.info,  Node: Grammar File,  Next: Interface,  Prev: Examples,  Up: Top
  508.  
  509. Bison Grammar Files
  510. *******************
  511.  
  512. Bison takes as input a context-free grammar specification and
  513. produces a C-language function that recognizes correct instances of
  514. the grammar.
  515.  
  516. The Bison grammar input file conventionally has a name ending in `.y'.
  517.  
  518. * Menu:
  519.  
  520. * Grammar Outline::    Overall layout of the grammar file.
  521. * Symbols::            Terminal and nonterminal symbols.
  522. * Rules::              How to write grammar rules.
  523. * Recursion::           Writing recursive rules.
  524. * Semantics::          Semantic values and actions.
  525. * Declarations::       All kinds of Bison declarations are described here.
  526. * Multiple Parsers::   Putting more than one Bison parser in one program.
  527.  
  528.  
  529. 
  530. File: bison.info,  Node: Grammar Outline,  Next: Symbols,  Prev: Grammar File,  Up: Grammar File
  531.  
  532. Outline of a Bison Grammar
  533. ==========================
  534.  
  535. A Bison grammar file has four main sections, shown here with the
  536. appropriate delimiters:
  537.  
  538.      %{
  539.      C DECLARATIONS
  540.      %}
  541.      
  542.      BISON DECLARATIONS
  543.      
  544.      %%
  545.      GRAMMAR RULES
  546.      %%
  547.      
  548.      ADDITIONAL C CODE
  549.  
  550. Comments enclosed in `/* ... */' may appear in any of the sections.
  551.  
  552. * Menu:
  553.  
  554. * C Declarations::      Syntax and usage of the C declarations section.
  555. * Bison Declarations::  Syntax and usage of the Bison declarations section.
  556. * Grammar Rules::       Syntax and usage of the grammar rules section.
  557. * C Code::              Syntax and usage of the additional C code section.
  558.  
  559.  
  560. 
  561. File: bison.info,  Node: C Declarations,  Next: Bison Declarations,  Prev: Grammar Outline,  Up: Grammar Outline
  562.  
  563. The C Declarations Section
  564. --------------------------
  565.  
  566. The C DECLARATIONS section contains macro definitions and
  567. declarations of functions and variables that are used in the actions
  568. in the grammar rules.  These are copied to the beginning of the
  569. parser file so that they precede the definition of `yylex'.  You can
  570. use `#include' to get the declarations from a header file.  If you
  571. don't need any C declarations, you may omit the `%{' and `%}'
  572. delimiters that bracket this section.
  573.  
  574.  
  575. 
  576. File: bison.info,  Node: Bison Declarations,  Next: Grammar Rules,  Prev: C Declarations,  Up: Grammar Outline
  577.  
  578. The Bison Declarations Section
  579. ------------------------------
  580.  
  581. The BISON DECLARATIONS section contains declarations that define
  582. terminal and nonterminal symbols, specify precedence, and so on.  In
  583. some simple grammars you may not need any declarations.  *Note
  584. Declarations::.
  585.  
  586.  
  587. 
  588. File: bison.info,  Node: Grammar Rules,  Next: C Code,  Prev: Bison Declarations,  Up: Grammar Outline
  589.  
  590. The Grammar Rules Section
  591. -------------------------
  592.  
  593. The "grammar rules" section contains one or more Bison grammar rules,
  594. and nothing else.  *Note Rules::.
  595.  
  596. There must always be at least one grammar rule, and the first `%%'
  597. (which precedes the grammar rules) may never be omitted even if it is
  598. the first thing in the file.
  599.  
  600.  
  601. 
  602. File: bison.info,  Node: C Code,  Prev: Grammar Rules,  Up: Grammar Outline
  603.  
  604. The Additional C Code Section
  605. -----------------------------
  606.  
  607. The ADDITIONAL C CODE section is copied verbatim to the end of the
  608. parser file, just as the C DECLARATIONS section is copied to the
  609. beginning.  This is the most convenient place to put anything that
  610. you want to have in the parser file but which need not come before
  611. the definition of `yylex'.  For example, the definitions of `yylex'
  612. and `yyerror' often go here.  *Note Interface::.
  613.  
  614. If the last section is empty, you may omit the `%%' that separates it
  615. from the grammar rules.
  616.  
  617. The Bison parser itself contains many static variables whose names
  618. start with `yy' and many macros whose names start with `YY'.  It is a
  619. good idea to avoid using any such names (except those documented in
  620. this manual) in the additional C code section of the grammar file.
  621.  
  622.  
  623. 
  624. File: bison.info,  Node: Symbols,  Next: Rules,  Prev: Grammar Outline,  Up: Grammar File
  625.  
  626. Symbols, Terminal and Nonterminal
  627. =================================
  628.  
  629. "Symbols" in Bison grammars represent the grammatical classifications
  630. of the language.
  631.  
  632. A "terminal symbol" (also known as a "token type") represents a class
  633. of syntactically equivalent tokens.  You use the symbol in grammar
  634. rules to mean that a token in that class is allowed.  The symbol is
  635. represented in the Bison parser by a numeric code, and the `yylex'
  636. function returns a token type code to indicate what kind of token has
  637. been read.  You don't need to know what the code value is; you can
  638. use the symbol to stand for it.
  639.  
  640. A "nonterminal symbol" stands for a class of syntactically equivalent
  641. groupings.  The symbol name is used in writing grammar rules.  By
  642. convention, it should be all lower case.
  643.  
  644. Symbol names can contain letters, digits (not at the beginning),
  645. underscores and periods.  Periods make sense only in nonterminals.
  646.  
  647. There are two ways of writing terminal symbols in the grammar:
  648.  
  649.    * A "named token type" is written with an identifier, like an
  650.      identifier in C.  By convention, it should be all upper case. 
  651.      Each such name must be defined with a Bison declaration such as
  652.      `%token'.  *Note Token Decl::.
  653.  
  654.    * A "character token type" (or "literal token") is written in the
  655.      grammar using the same syntax used in C for character constants;
  656.      for example, `'+'' is a character token type.  A character token
  657.      type doesn't need to be declared unless you need to specify its
  658.      semantic value data type (*note Value Type::.), associativity,
  659.      or precedence (*note Precedence::.).
  660.  
  661.      By convention, a character token type is used only to represent
  662.      a token that consists of that particular character.  Thus, the
  663.      token type `'+'' is used to represent the character `+' as a
  664.      token.  Nothing enforces this convention, but if you depart from
  665.      it, your program will confuse other readers.
  666.  
  667.      All the usual escape sequences used in character literals in C
  668.      can be used in Bison as well, but you must not use the null
  669.      character as a character literal because its ASCII code, zero,
  670.      is the code `yylex' returns for end-of-input (*note Calling
  671.      Convention::.).
  672.  
  673. How you choose to write a terminal symbol has no effect on its
  674. grammatical meaning.  That depends only on where it appears in rules
  675. and on when the parser function returns that symbol.
  676.  
  677. The value returned by `yylex' is always one of the terminal symbols
  678. (or 0 for end-of-input).  Whichever way you write the token type in
  679. the grammar rules, you write it the same way in the definition of
  680. `yylex'.  The numeric code for a character token type is simply the
  681. ASCII code for the character, so `yylex' can use the identical
  682. character constant to generate the requisite code.  Each named token
  683. type becomes a C macro in the parser file, so `yylex' can use the
  684. name to stand for the code.  (This is why periods don't make sense in
  685. terminal symbols.)  *Note Calling Convention::.
  686.  
  687. If `yylex' is defined in a separate file, you need to arrange for the
  688. token-type macro definitions to be available there.  Use the `-d'
  689. option when you run Bison, so that it will write these macro
  690. definitions into a separate header file `NAME.tab.h' which you can
  691. include in the other source files that need it.  *Note Invocation::.
  692.  
  693. The symbol `error' is a terminal symbol reserved for error recovery
  694. (*note Error Recovery::.); you shouldn't use it for any other purpose.
  695. In particular, `yylex' should never return this value.
  696.  
  697.  
  698. 
  699. File: bison.info,  Node: Rules,  Next: Recursion,  Prev: Symbols,  Up: Grammar File
  700.  
  701. Syntax of Grammar Rules
  702. =======================
  703.  
  704. A Bison grammar rule has the following general form:
  705.  
  706.      RESULT: COMPONENTS...
  707.              ;
  708.  
  709. where RESULT is the nonterminal symbol that this rule describes and
  710. COMPONENTS are various terminal and nonterminal symbols that are put
  711. together by this rule (*note Symbols::.).  For example,
  712.  
  713.      exp:      exp '+' exp
  714.              ;
  715.  
  716. says that two groupings of type `exp', with a `+' token in between,
  717. can be combined into a larger grouping of type `exp'.
  718.  
  719. Whitespace in rules is significant only to separate symbols.  You can
  720. add extra whitespace as you wish.
  721.  
  722. Scattered among the components can be ACTIONS that determine the
  723. semantics of the rule.  An action looks like this:
  724.  
  725.      {C STATEMENTS}
  726.  
  727. Usually there is only one action and it follows the components. 
  728. *Note Actions::.
  729.  
  730. Multiple rules for the same RESULT can be written separately or can
  731. be joined with the vertical-bar character `|' as follows:
  732.  
  733.      RESULT:   RULE1-COMPONENTS...
  734.              | RULE2-COMPONENTS...
  735.              ...
  736.              ;
  737.  
  738. They are still considered distinct rules even when joined in this way.
  739.  
  740. If COMPONENTS in a rule is empty, it means that RESULT can match the
  741. empty string.  For example, here is how to define a comma-separated
  742. sequence of zero or more `exp' groupings:
  743.  
  744.      expseq:   /* empty */
  745.              | expseq1
  746.              ;
  747.      
  748.      expseq1:  exp
  749.              | expseq1 ',' exp
  750.              ;
  751.  
  752. It is customary to write a comment `/* empty */' in each rule with no
  753. components.
  754.  
  755.  
  756. 
  757. File: bison.info,  Node: Recursion,  Next: Semantics,  Prev: Rules,  Up: Grammar File
  758.  
  759. Recursive Rules
  760. ===============
  761.  
  762. A rule is called "recursive" when its RESULT nonterminal appears also
  763. on its right hand side.  Nearly all Bison grammars need to use
  764. recursion, because that is the only way to define a sequence of any
  765. number of somethings.  Consider this recursive definition of a
  766. comma-separated sequence of one or more expressions:
  767.  
  768.      expseq1:  exp
  769.              | expseq1 ',' exp
  770.              ;
  771.  
  772. Since the recursive use of `expseq1' is the leftmost symbol in the
  773. right hand side, we call this "left recursion".  By contrast, here
  774. the same construct is defined using "right recursion":
  775.  
  776.      expseq1:  exp
  777.              | exp ',' expseq1
  778.              ;
  779.  
  780. Any kind of sequence can be defined using either left recursion or
  781. right recursion, but you should always use left recursion, because it
  782. can parse a sequence of any number of elements with bounded stack
  783. space.  Right recursion uses up space on the Bison stack in
  784. proportion to the number of elements in the sequence, because all the
  785. elements must be shifted onto the stack before the rule can be
  786. applied even once.  *Note Algorithm::, for further explanation of this.
  787.  
  788. "Indirect" or "mutual" recursion occurs when the result of the rule
  789. does not appear directly on its right hand side, but does appear in
  790. rules for other nonterminals which do appear on its right hand side. 
  791. For example:
  792.  
  793.      expr:     primary
  794.              | primary '+' primary
  795.              ;
  796.      
  797.      primary:  constant
  798.              | '(' expr ')'
  799.              ;
  800.  
  801. defines two mutually-recursive nonterminals, since each refers to the
  802. other.
  803.  
  804.  
  805. 
  806. File: bison.info,  Node: Semantics,  Next: Declarations,  Prev: Recursion,  Up: Grammar File
  807.  
  808. The Semantics of the Language
  809. =============================
  810.  
  811. The grammar rules for a language determine only the syntax.  The
  812. semantics are determined by the semantic values associated with
  813. various tokens and groupings, and by the actions taken when various
  814. groupings are recognized.
  815.  
  816. For example, the calculator calculates properly because the value
  817. associated with each expression is the proper number; it adds
  818. properly because the action for the grouping `X + Y' is to add the
  819. numbers associated with X and Y.
  820.  
  821. * Menu:
  822.  
  823. * Value Type::       Specifying one data type for all semantic values.
  824. * Multiple Types::   Specifying several alternative data types.
  825. * Actions::          An action is the semantic definition of a grammar rule.
  826. * Action Types::     Specifying data types for actions to operate on.
  827. * Mid-Rule Actions:: Most actions go at the end of a rule.
  828.                       This says when, why and how to use the exceptional
  829.                       action in the middle of a rule.
  830.  
  831.  
  832. 
  833. File: bison.info,  Node: Value Type,  Next: Multiple Types,  Prev: Semantics,  Up: Semantics
  834.  
  835. The Data Types of Semantic Values
  836. ---------------------------------
  837.  
  838. In a simple program it may be sufficient to use the same data type
  839. for the semantic values of all language constructs.  This was true in
  840. the RPN and infix calculator examples (*note RPN Calc::.).
  841.  
  842. Bison's default is to use type `int' for all semantic values.  To
  843. specify some other type, define `YYSTYPE' as a macro, like this:
  844.  
  845.      #define YYSTYPE double
  846.  
  847. This macro definition must go in the C declarations section of the
  848. grammar file (*note Grammar Outline::.).
  849.  
  850.  
  851. 
  852. File: bison.info,  Node: Multiple Types,  Next: Actions,  Prev: Value Type,  Up: Semantics
  853.  
  854. More Than One Type for Semantic Values
  855. --------------------------------------
  856.  
  857. In most programs, you will need different data types for different
  858. kinds of tokens and groupings.  For example, a numeric constant may
  859. need type `int' or `long', while a string constant needs type `char
  860. *', and an identifier might need a pointer to an entry in the symbol
  861. table.
  862.  
  863. To use more than one data type for semantic values in one parser,
  864. Bison requires you to do two things:
  865.  
  866.    * Specify the entire collection of possible data types, with the
  867.      `%union' Bison declaration (*note Union Decl::.).
  868.  
  869.    * Choose one of those types for each symbol (terminal or
  870.      nonterminal) for which semantic values are used.  This is done
  871.      for tokens with the `%token' Bison declaration (*note Token
  872.      Decl::.) and for groupings with the `%type' Bison declaration
  873.      (*note Type Decl::.).
  874.  
  875.  
  876. 
  877. File: bison.info,  Node: Actions,  Next: Action Types,  Prev: Multiple Types,  Up: Semantics
  878.  
  879. Actions
  880. -------
  881.  
  882. An action accompanies a syntactic rule and contains C code to be
  883. executed each time an instance of that rule is recognized.  The task
  884. of most actions is to compute a semantic value for the grouping built
  885. by the rule from the semantic values associated with tokens or
  886. smaller groupings.
  887.  
  888. An action consists of C statements surrounded by braces, much like a
  889. compound statement in C.  It can be placed at any position in the
  890. rule; it is executed at that position.  Most rules have just one
  891. action at the end of the rule, following all the components.  Actions
  892. in the middle of a rule are tricky and used only for special purposes
  893. (*note Mid-Rule Actions::.).
  894.  
  895. The C code in an action can refer to the semantic values of the
  896. components matched by the rule with the construct `$N', which stands
  897. for the value of the Nth component.  The semantic value for the
  898. grouping being constructed is `$$'.  (Bison translates both of these
  899. constructs into array element references when it copies the actions
  900. into the parser file.)
  901.  
  902. Here is a typical example:
  903.  
  904.      exp:    ...
  905.              | exp '+' exp
  906.                  { $$ = $1 + $3; }
  907.  
  908. This rule constructs an `exp' from two smaller `exp' groupings
  909. connected by a plus-sign token.  In the action, `$1' and `$3' refer
  910. to the semantic values of the two component `exp' groupings, which
  911. are the first and third symbols on the right hand side of the rule. 
  912. The sum is stored into `$$' so that it becomes the semantic value of
  913. the addition-expression just recognized by the rule.  If there were a
  914. useful semantic value associated with the `+' token, it could be
  915. referred to as `$2'.
  916.  
  917. `$N' with N zero or negative is allowed for reference to tokens and
  918. groupings on the stack *before* those that match the current rule. 
  919. This is a very risky practice, and to use it reliably you must be
  920. certain of the context in which the rule is applied.  Here is a case
  921. in which you can use this reliably:
  922.  
  923.      foo:      expr bar '+' expr  { ... }
  924.              | expr bar '-' expr  { ... }
  925.              ;
  926.      
  927.      bar:      /* empty */
  928.              { previous_expr = $0; }
  929.              ;
  930.  
  931. As long as `bar' is used only in the fashion shown here, `$0' always
  932. refers to the `expr' which precedes `bar' in the definition of `foo'.
  933.  
  934.  
  935. 
  936. File: bison.info,  Node: Action Types,  Next: Mid-Rule Actions,  Prev: Actions,  Up: Semantics
  937.  
  938. Data Types of Values in Actions
  939. -------------------------------
  940.  
  941. If you have chosen a single data type for semantic values, the `$$'
  942. and `$N' constructs always have that data type.
  943.  
  944. If you have used `%union' to specify a variety of data types, then
  945. you must declare a choice among these types for each terminal or
  946. nonterminal symbol that can have a semantic value.  Then each time
  947. you use `$$' or `$N', its data type is determined by which symbol it
  948. refers to in the rule.  In this example,
  949.  
  950.      exp:    ...
  951.              | exp '+' exp
  952.                  { $$ = $1 + $3; }
  953.  
  954. `$3' and `$$' refer to instances of `exp', so they all have the data
  955. type declared for the nonterminal symbol `exp'.  If `$2' were used,
  956. it would have the data type declared for the terminal symbol `'+'',
  957. whatever that might be.
  958.  
  959. Alternatively, you can specify the data type when you refer to the
  960. value, by inserting `<TYPE>' after the `$' at the beginning of the
  961. reference.  For example, if you have defined types as shown here:
  962.  
  963.      %union {
  964.        int itype;
  965.        double dtype;
  966.      }
  967.  
  968. then you can write `$<itype>1' to refer to the first subunit of the
  969. rule as an integer, or `$<dtype>1' to refer to it as a double.
  970.  
  971.  
  972. 
  973. File: bison.info,  Node: Mid-Rule Actions,  Prev: Action Types,  Up: Semantics
  974.  
  975. Actions in Mid-Rule
  976. -------------------
  977.  
  978. Occasionally it is useful to put an action in the middle of a rule. 
  979. These actions are written just like usual end-of-rule actions, but
  980. they are executed before the parser even recognizes the following
  981. components.
  982.  
  983. A mid-rule action may refer to the components preceding it using
  984. `$N', but it may not refer to subsequent components because it is run
  985. before they are parsed.
  986.  
  987. The mid-rule action itself counts as one of the components of the rule.
  988. This makes a difference when there is another action later in the
  989. same rule (and usually there is another at the end): you have to
  990. count the actions along with the symbols when working out which
  991. number N to use in `$N'.
  992.  
  993. The mid-rule action can also have a semantic value.  This can be set
  994. within that action by an assignment to `$$', and can referred to by
  995. later actions using `$N'.  Since there is no symbol to name the
  996. action, there is no way to declare a data type for the value in
  997. advance, so you must use the `$<...>' construct to specify a data
  998. type each time you refer to this value.
  999.  
  1000. Here is an example from a hypothetical compiler, handling a `let'
  1001. statement that looks like `let (VARIABLE) STATEMENT' and serves to
  1002. create a variable named VARIABLE temporarily for the duration of
  1003. STATEMENT.  To parse this construct, we must put VARIABLE into the
  1004. symbol table while STATEMENT is parsed, then remove it afterward. 
  1005. Here is how it is done:
  1006.  
  1007.      stmt:   LET '(' var ')'
  1008.                      { $<context>$ = push_context ();
  1009.                        declare_variable ($3); }
  1010.              stmt    { $$ = $6;
  1011.                        pop_context ($<context>5); }
  1012.  
  1013. As soon as `let (VARIABLE)' has been recognized, the first action is
  1014. run.  It saves a copy of the current semantic context (the list of
  1015. accessible variables) as its semantic value, using alternative
  1016. `context' in the data-type union.  Then it calls `declare_variable'
  1017. to add the new variable to that list.  Once the first action is
  1018. finished, the embedded statement `stmt' can be parsed.  Note that the
  1019. mid-rule action is component number 5, so the `stmt' is component
  1020. number 6.
  1021.  
  1022. After the embedded statement is parsed, its semantic value becomes
  1023. the value of the entire `let'-statement.  Then the semantic value
  1024. from the earlier action is used to restore the prior list of
  1025. variables.  This removes the temporary `let'-variable from the list
  1026. so that it won't appear to exist while the rest of the program is
  1027. parsed.
  1028.  
  1029. Taking action before a rule is completely recognized often leads to
  1030. conflicts since the parser must commit to a parse in order to execute
  1031. the action.  For example, the following two rules, without mid-rule
  1032. actions, can coexist in a working parser because the parser can shift
  1033. the open-brace token and look at what follows before deciding whether
  1034. there is a declaration or not:
  1035.  
  1036.      compound: '{' declarations statements '}'
  1037.              | '{' statements '}'
  1038.              ;
  1039.  
  1040. But when we add a mid-rule action as follows, the rules become
  1041. nonfunctional:
  1042.  
  1043.      compound: { prepare_for_local_variables (); }
  1044.                '{' declarations statements '}'
  1045.  
  1046.              | '{' statements '}'
  1047.              ;
  1048.  
  1049. Now the parser is forced to decide whether to run the mid-rule action
  1050. when it has read no farther than the open-brace.  In other words, it
  1051. must commit to using one rule or the other, without sufficient
  1052. information to do it correctly.  (The open-brace token is what is
  1053. called the "look-ahead" token at this time, since the parser is still
  1054. deciding what to do about it.  *Note Look-Ahead::.)
  1055.  
  1056. You might think that you could correct the problem by putting
  1057. identical actions into the two rules, like this:
  1058.  
  1059.      compound: { prepare_for_local_variables (); }
  1060.                '{' declarations statements '}'
  1061.              | { prepare_for_local_variables (); }
  1062.                '{' statements '}'
  1063.              ;
  1064.  
  1065. But this does not help, because Bison does not realize that the two
  1066. actions are identical.  (Bison never tries to understand the C code
  1067. in an action.)
  1068.  
  1069. If the grammar is such that a declaration can be distinguished from a
  1070. statement by the first token (which is true in C), then one solution
  1071. which does work is to put the action after the open-brace, like this:
  1072.  
  1073.      compound: '{' { prepare_for_local_variables (); }
  1074.                declarations statements '}'
  1075.              | '{' statements '}'
  1076.              ;
  1077.  
  1078. Now the first token of the following declaration or statement, which
  1079. would in any case tell Bison which rule to use, can still do so.
  1080.  
  1081. Another solution is to bury the action inside a nonterminal symbol
  1082. which serves as a subroutine:
  1083.  
  1084.      subroutine: /* empty */
  1085.                { prepare_for_local_variables (); }
  1086.              ;
  1087.      
  1088.      compound: subroutine
  1089.                '{' declarations statements '}'
  1090.              | subroutine
  1091.                '{' statements '}'
  1092.              ;
  1093.  
  1094. Now Bison can execute the action in the rule for `subroutine' without
  1095. deciding which rule for `compound' it will eventually use.  Note that
  1096. the action is now at the end of its rule.  Any mid-rule action can be
  1097. converted to an end-of-rule action in this way, and this is what
  1098. Bison actually does to implement mid-rule actions.
  1099.  
  1100.  
  1101. 
  1102. File: bison.info,  Node: Declarations,  Next: Multiple Parsers,  Prev: Semantics,  Up: Grammar File
  1103.  
  1104. Bison Declarations
  1105. ==================
  1106.  
  1107. The "Bison declarations" section of a Bison grammar defines the
  1108. symbols used in formulating the grammar and the data types of
  1109. semantic values.  *Note Symbols::.
  1110.  
  1111. All token type names (but not single-character literal tokens such as
  1112. `'+'' and `'*'') must be declared.  Nonterminal symbols must be
  1113. declared if you need to specify which data type to use for the
  1114. semantic value (*note Multiple Types::.).
  1115.  
  1116. The first rule in the file also specifies the start symbol, by default.
  1117. If you want some other symbol to be the start symbol, you must
  1118. declare it explicitly (*note Language and Grammar::.).
  1119.  
  1120. * Menu:
  1121.  
  1122. * Token Decl::       Declaring terminal symbols.
  1123. * Precedence Decl::  Declaring terminals with precedence and associativity.
  1124. * Union Decl::       Declaring the set of all semantic value types.
  1125. * Type Decl::        Declaring the choice of type for a nonterminal symbol.
  1126. * Expect Decl::      Suppressing warnings about shift/reduce conflicts.
  1127. * Start Decl::       Specifying the start symbol.
  1128. * Pure Decl::        Requesting a reentrant parser.
  1129. * Decl Summary::     Table of all Bison declarations.
  1130.  
  1131.  
  1132. 
  1133. File: bison.info,  Node: Token Decl,  Next: Precedence Decl,  Prev: Declarations,  Up: Declarations
  1134.  
  1135. Declaring Token Type Names
  1136. --------------------------
  1137.  
  1138. The basic way to declare a token type name (terminal symbol) is as
  1139. follows:
  1140.  
  1141.      %token NAME
  1142.  
  1143. Bison will convert this into a `#define' directive in the parser, so
  1144. that the function `yylex' (if it is in this file) can use the name
  1145. NAME to stand for this token type's code.
  1146.  
  1147. Alternatively you can use `%left', `%right', or `%nonassoc' instead
  1148. of `%token', if you wish to specify precedence.  *Note Precedence
  1149. Decl::.
  1150.  
  1151. You can explicitly specify the numeric code for a token type by
  1152. appending an integer value in the field immediately following the
  1153. token name:
  1154.  
  1155.      %token NUM 300
  1156.  
  1157. It is generally best, however, to let Bison choose the numeric codes
  1158. for all token types.  Bison will automatically select codes that
  1159. don't conflict with each other or with ASCII characters.
  1160.  
  1161. In the event that the stack type is a union, you must augment the
  1162. `%token' or other token declaration to include the data type
  1163. alternative delimited by angle-brackets (*note Multiple Types::.). 
  1164. For example:
  1165.  
  1166.      %union {              /* define stack type */
  1167.        double val;
  1168.        symrec *tptr;
  1169.      }
  1170.      %token <val> NUM      /* define token NUM and its type */
  1171.  
  1172.  
  1173. 
  1174. File: bison.info,  Node: Precedence Decl,  Next: Union Decl,  Prev: Token Decl,  Up: Declarations
  1175.  
  1176. Declaring Operator Precedence
  1177. -----------------------------
  1178.  
  1179. Use the `%left', `%right' or `%nonassoc' declaration to declare a
  1180. token and specify its precedence and associativity, all at once. 
  1181. These are called "precedence declarations".  *Note Precedence::, for
  1182. general information on operator precedence.
  1183.  
  1184. The syntax of a precedence declaration is the same as that of
  1185. `%token': either
  1186.  
  1187.      %left SYMBOLS...
  1188.  
  1189.  or
  1190.  
  1191.      %left <TYPE> SYMBOLS...
  1192.  
  1193.  And indeed any of these declarations serves the purposes of `%token'.
  1194. But in addition, they specify the associativity and relative
  1195. precedence for all the SYMBOLS:
  1196.  
  1197.    * The associativity of an operator OP determines how repeated uses
  1198.      of the operator nest: whether `X OP Y OP Z' is parsed by
  1199.      grouping X with Y first or by grouping Y with Z first.  `%left'
  1200.      specifies left-associativity (grouping X with Y first) and
  1201.      `%right' specifies right-associativity (grouping Y with Z
  1202.      first).  `%nonassoc' specifies no associativity, which means
  1203.      that `X OP Y OP Z' is considered a syntax error.
  1204.  
  1205.    * The precedence of an operator determines how it nests with other
  1206.      operators.  All the tokens declared in a single precedence
  1207.      declaration have equal precedence and nest together according to
  1208.      their associativity.  When two tokens declared in different
  1209.      precedence declarations associate, the one declared later has
  1210.      the higher precedence and is grouped first.
  1211.  
  1212.  
  1213. 
  1214. File: bison.info,  Node: Union Decl,  Next: Type Decl,  Prev: Precedence Decl,  Up: Declarations
  1215.  
  1216. Declaring the Collection of Value Types
  1217. ---------------------------------------
  1218.  
  1219. The `%union' declaration specifies the entire collection of possible
  1220. data types for semantic values.  The keyword `%union' is followed by
  1221. a pair of braces containing the same thing that goes inside a `union'
  1222. in C.  For example:
  1223.  
  1224.      %union {
  1225.        double val;
  1226.        symrec *tptr;
  1227.      }
  1228.  
  1229. This says that the two alternative types are `double' and `symrec *'.
  1230. They are given names `val' and `tptr'; these names are used in the
  1231. `%token' and `%type' declarations to pick one of the types for a
  1232. terminal or nonterminal symbol (*note Type Decl::.).
  1233.  
  1234. Note that, unlike making a `union' declaration in C, you do not write
  1235. a semicolon after the closing brace.
  1236.  
  1237.  
  1238. 
  1239. File: bison.info,  Node: Type Decl,  Next: Expect Decl,  Prev: Union Decl,  Up: Declarations
  1240.  
  1241. Declaring Value Types of Nonterminal Symbols
  1242. --------------------------------------------
  1243.  
  1244. When you use `%union' to specify multiple value types, you must
  1245. declare the value type of each nonterminal symbol for which values
  1246. are used.  This is done with a `%type' declaration, like this:
  1247.  
  1248.      %type <TYPE> NONTERMINAL...
  1249.  
  1250.  Here NONTERMINAL is the name of a nonterminal symbol, and TYPE is the
  1251. name given in the `%union' to the alternative that you want (*note
  1252. Union Decl::.).  You can give any number of nonterminal symbols in
  1253. the same `%type' declaration, if they have the same value type.  Use
  1254. spaces to separate the symbol names.
  1255.  
  1256.  
  1257. 
  1258. File: bison.info,  Node: Expect Decl,  Next: Start Decl,  Prev: Type Decl,  Up: Declarations
  1259.  
  1260. Preventing Warnings about Conflicts
  1261. -----------------------------------
  1262.  
  1263. Bison normally warns if there are any conflicts in the grammar (*note
  1264. Shift/Reduce::.), but most real grammars have harmless shift/reduce
  1265. conflicts which are resolved in a predictable way and would be
  1266. difficult to eliminate.  It is desirable to suppress the warning
  1267. about these conflicts unless the number of conflicts changes.  You
  1268. can do this with the `%expect' declaration.
  1269.  
  1270. The declaration looks like this:
  1271.  
  1272.      %expect N
  1273.  
  1274. Here N is a decimal integer.  The declaration says there should be no
  1275. warning if there are N shift/reduce conflicts and no reduce/reduce
  1276. conflicts.  The usual warning is given if there are either more or
  1277. fewer conflicts, or if there are any reduce/reduce conflicts.
  1278.  
  1279. In general, using `%expect' involves these steps:
  1280.  
  1281.    * Compile your grammar without `%expect'.  Use the `-v' option to
  1282.      get a verbose list of where the conflicts occur.  Bison will
  1283.      also print the number of conflicts.
  1284.  
  1285.    * Check each of the conflicts to make sure that Bison's default
  1286.      resolution is what you really want.  If not, rewrite the grammar
  1287.      and go back to the beginning.
  1288.  
  1289.    * Add an `%expect' declaration, copying the number N from the
  1290.      number which Bison printed.
  1291.  
  1292. Now Bison will stop annoying you about the conflicts you have
  1293. checked, but it will warn you again if changes in the grammer result
  1294. in additional conflicts.
  1295.  
  1296.  
  1297. 
  1298. File: bison.info,  Node: Start Decl,  Next: Pure Decl,  Prev: Expect Decl,  Up: Declarations
  1299.  
  1300. Declaring the Start-Symbol
  1301. --------------------------
  1302.  
  1303. Bison assumes by default that the start symbol for the grammar is the
  1304. first nonterminal specified in the grammar specification section. 
  1305. The programmer may override this restriction with the `%start'
  1306. declaration as follows:
  1307.  
  1308.      %start SYMBOL
  1309.  
  1310.  
  1311. 
  1312. File: bison.info,  Node: Pure Decl,  Next: Decl Summary,  Prev: Start Decl,  Up: Declarations
  1313.  
  1314. Requesting a Pure (Reentrant) Parser
  1315. ------------------------------------
  1316.  
  1317. A "reentrant" program is one which does not alter in the course of
  1318. execution; in other words, it consists entirely of "pure" (read-only)
  1319. code.  Reentrancy is important whenever asynchronous execution is
  1320. possible; for example, a nonreentrant program may not be safe to call
  1321. from a signal handler.  In systems with multiple threads of control,
  1322. a nonreentrant program must be called only within interlocks.
  1323.  
  1324. The Bison parser is not normally a reentrant program, because it uses
  1325. statically allocated variables for communication with `yylex'.  These
  1326. variables include `yylval' and `yylloc'.
  1327.  
  1328. The Bison declaration `%pure_parser' says that you want the parser to
  1329. be reentrant.  It looks like this:
  1330.  
  1331.      %pure_parser
  1332.  
  1333. The effect is that the the two communication variables become local
  1334. variables in `yyparse', and a different calling convention is used
  1335. for the lexical analyzer function `yylex'.  *Note Pure Calling::, for
  1336. the details of this.  The variable `yynerrs' also becomes local in
  1337. `yyparse' (*note Error Reporting::.).  The convention for calling
  1338. `yyparse' itself is unchanged.
  1339.  
  1340.  
  1341. 
  1342. File: bison.info,  Node: Decl Summary,  Prev: Pure Decl,  Up: Declarations
  1343.  
  1344. Bison Declaration Summary
  1345. -------------------------
  1346.  
  1347. Here is a summary of all Bison declarations:
  1348.  
  1349. `%union'
  1350.      Declare the collection of data types that semantic values may
  1351.      have (*note Union Decl::.).
  1352.  
  1353. `%token'
  1354.      Declare a terminal symbol (token type name) with no precedence
  1355.      or associativity specified (*note Token Decl::.).
  1356.  
  1357. `%right'
  1358.      Declare a terminal symbol (token type name) that is
  1359.      right-associative (*note Precedence Decl::.).
  1360.  
  1361. `%left'
  1362.      Declare a terminal symbol (token type name) that is
  1363.      left-associative (*note Precedence Decl::.).
  1364.  
  1365. `%nonassoc'
  1366.      Declare a terminal symbol (token type name) that is
  1367.      nonassociative (using it in a way that would be associative is a
  1368.      syntax error) (*note Precedence Decl::.).
  1369.  
  1370. `%type'
  1371.      Declare the type of semantic values for a nonterminal symbol
  1372.      (*note Type Decl::.).
  1373.  
  1374. `%start'
  1375.      Specify the grammar's start symbol (*note Start Decl::.).
  1376.  
  1377. `%expect'
  1378.      Declare the expected number of shift-reduce conflicts (*note
  1379.      Expect Decl::.).
  1380.  
  1381. `%pure_parser'
  1382.      Request a pure (reentrant) parser program (*note Pure Decl::.).
  1383.  
  1384.  
  1385.